// pages/order/order.js
import {Cart} from '../cart/cart-model.js';
import {Order} from 'order-model.js';
import {Address} from 'address-model.js';
var cart = new Cart();
var order = new Order();
var address = new Address();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    var from = options.from;
    if(from == 'cart'){
      var productsArr;
      this.data.totalPrice = options.totalPrice;
  
      // 获取订单的商品信息，即购物车选中的商品
      var productsArr = cart.getCartDataFromLocal(true);
  
      // 获取用户地址信息
      address.getUserAddressInfo((addressInfo) => {
        this._bindAddressInfo(addressInfo);
      });
  
      this.setData({
        productsArr:productsArr,
        totalPrice:this.data.totalPrice,
        orderStatus: 0
      })
    }else{
      this.data.id = options.id
    }
  },

  /**
   * 编辑收货地址
   * @param {*} event 
   */
  editAddress: function(event) {
    var that = this;
    wx.chooseAddress({
      success: (result) => {
        var addressInfo = {
          name:result.userName,
          tel:result.telNumber,
          totalDetail:address.setAddressInfo(result)
        }
        that._bindAddressInfo(addressInfo);

        //保存地址
        address.submitAddress(result,(flag)=>{
          if(!flag) {
              that.showTips('操作提示','地址信息更新失败！');
          }
      });
      },
    })
  },

  /**
   * 绑定地址数据
   */
  _bindAddressInfo: function(addressInfo) {
    this.setData({
      addressInfo: addressInfo
    })
  },

  pay: function() {
    // 判断收货地址是否存在
    if (!this.data.addressInfo){
      this.showTips('下单提示','请填写收货地址');
    }

    // 第一次在购物车支付需要创建订单， orderStatus=0是没创建订单的状态
    if(this.data.orderStatus == 0){
      this._firstTimePay();
    }else{
      this._oneMoreTimePay();
    }
  },

  _firstTimePay: function() {
    var orderInfo = [],
    productInfo = this.data.productsArr;

    // 组装参数
    for (let i = 0; i < productInfo.length; i++) {
      orderInfo.push({
        product_id : productInfo[i].id,
        count : productInfo[i].counts,
      })
    }
    var that = this;
    // 支付分两步，生成订单号，然后拉起付款
    order.doOrder(orderInfo, (res) => {
      if (res.pass){

        // 更新订单状态
        var id = res.order_id;
        that.data.id = id;
        that.data.fromCartFlag = false;

        // 开始支付
        that._execPay(id);
      }else{

        // 下单失败
        that._orderFail(res);
      }
    })
  },

  // 进行支付操作
  _execPay: function(id) {
    if(!order.onPay) {
      this.showTips('支付提示','本产品仅用于演示，支付系统已屏蔽',false);//屏蔽支付，提示
      this.deleteProducts(); //将已经下单的商品从购物车删除

      // 假装付款成功
      var flag = false;
      wx.navigateTo({
          url: '../pay-result/pay-result?id=' + id + '&flag=' + flag + '&from=order'
      });
      return;
    }

    var that=this;
    order.execPay(id,(statusCode)=>{
        if(statusCode!=0){
            that.deleteProducts(); //将已经下单的商品从购物车删除
            var flag = statusCode == 2;
            wx.navigateTo({
                url: '../pay-result/pay-result?id=' + id + '&flag=' + flag + '&from=order'
            });
        }else{
          that.showTips('操作提示', '支付失败');
        }
    });
  },

  // 支付后，删除购物车中的商品
  deleteProducts:function() {
    var arr = this.data.productsArr, ids = [];
    for(let i=0;i<arr.length;i++){
      ids.push(arr[i].id);
  }
    cart.delete(ids);
  },

  /*
  * 提示窗口
  * params:
  * title - {string}标题
  * content - {string}内容
  * flag - {bool}是否跳转到 "我的页面"
  */
 showTips:function(title,content,flag){
  wx.showModal({
      title: title,
      content: content,
      showCancel:false,
      success: function(res) {
          if(flag) {
              wx.switchTab({
                  url: '/pages/my/my'
              });
          }
      }
  });
 },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.id) {
      var id = this.data.id;
      order.getOrderInfo(id, (data) => {
        this.setData({
          basicInfo:{
            orderTime:data.create_time,
            orderNo:data.order_no
          },
          orderStatus:data.status,
          productsArr:data.snap_items,
          totalPrice:data.total_price
        });

        var addressInfo = data.snap_address;
        addressInfo.totalDetail = address.setAddressInfo(addressInfo);
        this._bindAddressInfo(addressInfo);
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
})